package com.cefa.edu.controller;

import com.cefa.edu.common.result.FailureResult;
import com.cefa.edu.common.result.Result;
import com.cefa.edu.common.result.ReturnMessage;
import com.cefa.edu.common.result.SuccessResult;
import com.cefa.edu.dao.OrganRelationMapper;
import com.cefa.edu.dao.UserOrganRoleMapper;
import com.cefa.edu.pojo.Phase;
import com.cefa.edu.service.PhaseService;
import com.cefa.edu.service.ScheduledService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cc664 on 2018/8/10.
 * @aa 学习阶段controller
 */
@RestController
public class PhaseController {

    Logger logger= LoggerFactory.getLogger(PhaseController.class);//日志记录器
    @Autowired
    private PhaseService phaseService;
    @Autowired
    private UserOrganRoleMapper userOrganRoleMapper;
    @Autowired
    private OrganRelationMapper organRelationMapper;

    @Autowired
    private ScheduledService scheduledService;

    /**
     * @aa 根据教育学习阶段id 删除对应的教育学习阶段数据
     * @aa add by chaijian 2018-08-15
     * @return
     */
    @RequestMapping("/education/deletePhase")
    public Result<Map<String,Object>> deletePhase(@Param("phaseId") Integer phaseId) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("falt",true);
        try {

            //校验参数是否为空
            if(phaseId==null ||phaseId==0){
                result.put("falt",false);
                result.put("msg","参数phaseId不可为空！");
            }else {
                //判断将删除的学习阶段下，是否有班级 若有 不可删除
                result=isHaveClass(result,phaseId);
                if(null==result.get("msg")){
                    //删除班级
                    phaseService.deletePhase(phaseId);

                }else {
                    result.put("falt",false);
                }

            }

        }catch (Exception e){
            logger.error(e.getMessage());
            result.put("falt",false);
            result.put("msg",e.getMessage());
        }
        return new SuccessResult<>(new ReturnMessage("200", "success"), result);
    }

    //判断将删除的学习阶段下，是否有班级 若有 不可删除
    private Map<String,Object> isHaveClass(Map<String, Object> result, Integer phaseId) {
       // int count=userOrganRoleMapper.countUserOrganRoleByPhaseId(phaseId);
        int count=organRelationMapper.countOrganRelation(phaseId);
        if(count>0){
            result.put("msg","要删除的学习阶段下含有班级，不可删除该学习阶段！");
        }

        return result;
    }

    /**
     * @aa  添加学习阶段及阶段下的年级数据
     * @aa 参数：学习阶段中文字符
     */
    @RequestMapping(value = "/education/savePhaseGrades",method = RequestMethod.POST)
    public Result<String> savePhase(Phase phase, String gradeNames,String gradeSorts, Integer userId,Integer roleType){
        FailureResult<String> failureResult=new FailureResult<String>(new ReturnMessage("500","failure"));
        if(StringUtils.isNotBlank(gradeNames)){
          try{
              //校验参数userId和roleType是否为空
             if(validateUserIdAndRoleTypeParamsNotNull(userId,roleType)){
                  //校验学习阶段参数是否为空
                  if(validatePhasePropertyNotNull(phase)){

                      //判断所添加学习阶段是否已入库
                      List<Phase> phaseList= phaseService.getPhasesBySchoolId(phase.getSchoolId());
                      boolean flag=isHaveInMapList("gradeName",phase.getPhaseName(),phaseList);
                      if(!flag){
                          //判断学习阶段sort属性是否有值 若为空设置1
                          if(phase.getSort()==null||phase.getSort()==0){
                              //默认幼儿园sort=1 小学sort=2 初中=3 高中=4
                              //根据学校阶段 获取到对应的学校阶段集合
                              if("高中".equals(phase.getPhaseName())){
                                  phase.setSort(4);
                              }
                              if("初中".equals(phase.getPhaseName())){
                                  phase.setSort(3);
                              }
                              if("小学".equals(phase.getPhaseName())){
                                  phase.setSort(2);
                              }
                              if("幼儿园".equals(phase.getPhaseName())){
                                  phase.setSort(1);
                              }

                          }
                          //添加学习阶段及阶段下的年级数据
                          phaseService.savePhaseAndGrades(phase,gradeNames,userId,roleType,gradeSorts);

                          return new SuccessResult<String>(new ReturnMessage("200","success"),"数据添加成功！");
                      }else{
                          //所添加学习阶段已入库
                          logger.error("所要添加的学习阶段已添加过!");
                          failureResult.setData("所要添加的学习阶段已添加过!");
                          return failureResult;
                      }

                  }else {
                      logger.error("请检查学习阶段参数是否有为空的！");
                      failureResult.setData("请检查学习阶段参数是否有为空的！");
                      return failureResult;
                  }
              }else{
                  logger.error("请检查userId和roleType参数是否有为空的！");
                  failureResult.setData("请检查userId和roleType参数是否有为空的！");
                  return failureResult;
              }

          }catch(Exception e){
              logger.error("添加学习阶段数据时，出错！");
              e.printStackTrace();
              failureResult.setData("添加学习阶段数据时，出错！");
              return failureResult;
          }
        }else{
            failureResult.setData("添加学习阶段数据时，年级参数不可为空！");
            return failureResult;
        }

    }

    //校验参数userId和roleType是否为空
    private boolean validateUserIdAndRoleTypeParamsNotNull(Integer userId, Integer roleType) {

        if(userId==null||userId==0){
            return false;
        }
        if(roleType==null ||roleType==0){
            return false;
        }
        return true;
    }

    //判断MapList集合中是否有value变量接收的数据
    private boolean isHaveInMapList(String key, String value, List<Phase> phaseList) {
        if(phaseList!=null && phaseList.size()>0){
            String phaseName=null;
            for(Phase phase:phaseList){
                phaseName=phase.getPhaseName();
                if(StringUtils.isNotBlank(phaseName)){
                    if(value.equals(phaseName)){
                        return true;
                    }
                }

            }
        }
        return false;
    }

    //非空校验学习阶段参数
    private Boolean validatePhasePropertyNotNull(Phase phase) {
        //phase_name 、school_id不可为空
        if(StringUtils.isBlank(phase.getPhaseName())){
            return false;
        }
        if(phase.getSchoolId()==null ||phase.getSchoolId()==0){
            return false;
        }
        return true;

    }


    /**
     * @aa 学生年级升级 测试
     */
    @RequestMapping("/education/testGradeUpdate")
    public String testGradeUpdate(){
        scheduledService.studentCirculation2();
        return "successs";
    }

}
